package com.Action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import sun.misc.BASE64Decoder;
import transformFactory.OperateImage;

import com.Entity.FamiliesInfo;
import com.Entity.InviteMemberInfo;
import com.Entity.MemberInfo;
import com.Entity.UsersInfo;
import com.Entity.Page.Json;
import com.Service.FamiliesService;
import com.Service.InviteMemberService;
import com.Service.MemberService;
import com.Service.UserService;

public class FamiliesAction extends BaseAction implements ServletResponseAware {

	private int flag = 0;
	private HttpServletResponse response;// response对象

	@Autowired
	private FamiliesService familyService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private UserService userService;
	@Autowired
	private InviteMemberService inviteService;

	private List<UsersInfo> userlist = new ArrayList<UsersInfo>();
	private List<FamiliesInfo> familylist = new ArrayList<FamiliesInfo>();
	private List<MemberInfo> memberlist = new ArrayList<MemberInfo>();
	private List<InviteMemberInfo> invitelist = new ArrayList<InviteMemberInfo>();

	FamiliesInfo familyinfo1 = new FamiliesInfo();

	public List<UsersInfo> getUserlist() {
		return userlist;
	}

	public void setUserlist(List<UsersInfo> userlist) {
		this.userlist = userlist;
	}

	public FamiliesInfo getFamiliesinfo() {
		return familyinfo1;
	}

	public void setFamiliesinfo(FamiliesInfo familyinfo1) {
		this.familyinfo1 = familyinfo1;
	}

	public List<FamiliesInfo> getFamilylist() {
		return familylist;
	}

	public void setFamilylist(List<FamiliesInfo> familylist) {
		this.familylist = familylist;
	}

	public List<MemberInfo> getMemberlist() {
		return memberlist;
	}

	public void setMemberlist(List<MemberInfo> memberlist) {
		this.memberlist = memberlist;
	}

	public List<InviteMemberInfo> getInvitelist() {
		return invitelist;
	}

	public void setInvitelist(List<InviteMemberInfo> invitelist) {
		this.invitelist = invitelist;
	}

	// 创建家庭组
	public void createFamily() throws ParseException, IOException {

		PrintWriter out = response.getWriter();

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = ServletActionContext.getRequest()
					.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}

		JSONObject jsonObject = JSONObject.fromObject(jb.toString());
		JSONObject returnjson = new JSONObject();

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");

		String uploadPath;
		String familyname = jsonObject.getString("familyName");

		// familyname = new String(familyname.getBytes("ISO-8859-1"), "UTF-8");
		//
		// familyname = java.net.URLDecoder.decode(familyname,"UTF-8");

		flag = familyService.checkByfamilyName(familyname);
		if (flag != 0) {
			returnjson.put("success", false);
			returnjson.put("msg", "家庭组已存在！");
		} else {
			int adminid = jsonObject.getInt("userId");
			String sign = jsonObject.getString("signature");

			// sign = new String(sign.getBytes("ISO-8859-1"), "UTF-8");
			//
			// sign = java.net.URLDecoder.decode(sign,"UTF-8");

			FamiliesInfo familyinfo = new FamiliesInfo();

			familyinfo.setFamilyName(familyname);
			familyinfo.setAdminId(Integer.valueOf(adminid));
			if (null != sign && !sign.isEmpty()) {
				familyinfo.setSignature(sign);
			}
			familyinfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
			familyinfo.setMemberNum((short) 1);

			// ByteArrayInputStream is = new
			// ByteArrayInputStream(jsonObject.get("fileData").toString().getBytes());
			BASE64Decoder decoder = new BASE64Decoder();

			if (null != jsonObject.get("fileData")) {
				String imageStr = jsonObject.get("fileData").toString();
				System.out.println("imageStr:" + imageStr);
				byte[] isbyte = decoder.decodeBuffer(imageStr);
				System.out.println("isbyte:" + isbyte.toString());
				String path = ServletActionContext.getRequest()
						.getContextPath();
				String basePath = ServletActionContext.getRequest().getScheme()
						+ "://"
						+ ServletActionContext.getRequest().getServerName()
						+ ":"
						+ ServletActionContext.getRequest().getServerPort()
						+ path + "/";

				uploadPath = ServletActionContext.getServletContext()
						.getRealPath("/upload");
				File dirFile = new File(uploadPath);
				// 判断当前文件夹（路径）是否存在，如果不存在则创建
				if (!dirFile.exists()) {
					// dirFile.mkdirs();
					dirFile.mkdir();
				}
				// 为文件重命名
				String realfileName = java.util.UUID.randomUUID().toString();
				realfileName += ".png";
				File toFile = new File(uploadPath, realfileName);

				// logger.info("图片存入本地的路径="+uploadPath+"\\"+fileName);
				BufferedOutputStream stream = null;
				try {
					FileOutputStream os = new FileOutputStream(toFile);
					stream = new BufferedOutputStream(os);
					stream.write(isbyte);
				} finally {
					stream.close();
				}

				String srcImagePath = uploadPath + "/" + realfileName;
				String toImagePath = uploadPath + "/" + realfileName;

				OperateImage operateimage = new OperateImage();
				operateimage.reduceImageEqualProportion(srcImagePath,
						toImagePath, 1);

				// logger.info("图片存数据库的路径="+"images/clubUpload_img/"+topic.getTopicAuthorId()+fileName);
				// topic.setTopicImageUrl(basePath+"images/clubUpload_img/"+topic.getTopicAuthorId()+"/topicImg/"+fileName);

				// JSONObject returnjson=new JSONObject();
				String imageurl = basePath + "upload/" + realfileName;
				familyinfo.setFamilyImg(imageurl);
				returnjson.put("imageurl", imageurl);
			}
			this.familyService.save(familyinfo);

			UsersInfo user = new UsersInfo();
			user = userService.getById(Integer.valueOf(adminid));
			int familyId = familyService.checkByfamilyName(familyname);
			MemberInfo memberinfo = new MemberInfo();
			memberinfo.setFamilyId(familyId);
			memberinfo.setUserId(Integer.valueOf(adminid));
			this.memberService.save(memberinfo);

			returnjson.put("success", true);
			returnjson.put("msg", "新建家庭组成功！");

		}
		out.println(returnjson.toString());
		out.flush();
		out.close();
	}

	// 查看家庭组资料
	public void displayFamily() throws UnsupportedEncodingException,
			ParseException {

		// String
		// userid=ServletActionContext.getRequest().getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");

		if (null != familyid && !familyid.isEmpty()) {

			Json json = new Json();
			FamiliesInfo familyinfo = familyService.getById(Integer
					.valueOf(familyid));
			if (null != familyinfo) {
				Map<String, Object> map = new HashMap<String, Object>();

				int userid = familyinfo.getAdminId();
				UsersInfo user = this.userService.getById(userid);

				map.put("familyid", familyinfo.getFamilyId());
				map.put("familyName", familyinfo.getFamilyName());
				map.put("familyImg", familyinfo.getFamilyImg());
				map.put("adminid", familyinfo.getAdminId());
				map.put("adminName", user.getUserName());
				map.put("signature", familyinfo.getSignature());
				map.put("createTime", familyinfo.getCreateTime());
				map.put("memberNum", familyinfo.getMemberNum());

				json.setMsg("获取成功");
				json.setObj(map);
				json.setSuccess(true);
			} else {
				json.setMsg("获取失败");
				json.setSuccess(false);
			}
			writeJson(json);
		}
	}

	// 修改家庭组资料
	public void updateFamily() throws UnsupportedEncodingException,
			ParseException {

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");
		String familyname = ServletActionContext.getRequest().getParameter(
				"familyname");
		String signature = ServletActionContext.getRequest().getParameter(
				"signature");

		familyname = new String(familyname.getBytes("ISO-8859-1"), "UTF-8");
		signature = new String(signature.getBytes("ISO-8859-1"), "UTF-8");

		familyname = java.net.URLDecoder.decode(familyname, "UTF-8");
		signature = java.net.URLDecoder.decode(signature, "UTF-8");

		if (null != userid && !userid.isEmpty() && null != familyid
				&& !familyid.isEmpty()) {
			Json json = new Json();
			int adminid = Integer.valueOf(userid);

			FamiliesInfo familyinfo = familyService.getById(Integer
					.valueOf(familyid));
			if (null != familyinfo && adminid == familyinfo.getAdminId()) {

				if (null != familyname && !familyname.isEmpty()) {
					flag = familyService.checkByfamilyName(familyname);
					if (flag != 0) {
						json.setMsg("名字重复了！");
						json.setSuccess(false);
					} else {
						familyinfo.setFamilyName(familyname);
					}
				}

				if (null != signature && !signature.isEmpty()) {
					familyinfo.setSignature(signature);
				}

				this.familyService.save(familyinfo);
				json.setMsg("修改成功");
				json.setSuccess(true);
			} else {
				json.setMsg("你不是管理员，没有权限修改！");
				json.setSuccess(false);
			}
			writeJson(json);
		}
	}

	// 家庭组列表
	public void familyList() throws UnsupportedEncodingException,
			ParseException {

		ArrayList familylist = new ArrayList();

		ArrayList memberlist3 = new ArrayList();

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		// String
		// page=ServletActionContext.getRequest().getParameter("currpage");
		// String
		// rows=ServletActionContext.getRequest().getParameter("pagesize");

		Json json = new Json();
		memberlist = memberService.findByUserid(Integer.valueOf(userid));
		if (null != memberlist && !memberlist.isEmpty()) {
			for (int i = 0; i < memberlist.size(); i++) {
				System.out.println("家庭组" + memberlist.get(i).getFamilyId());
				familylist.add(familyService.getListByFamilyId(memberlist
						.get(i).getFamilyId()));

				List<MemberInfo> memberlist_temp = memberService
						.findByFamilyid(memberlist.get(i).getFamilyId());
				ArrayList<Map<String, Object>> memberlist2 = new ArrayList<Map<String, Object>>();
				for (MemberInfo member : memberlist_temp) {
					Map<String, Object> member_map = new HashMap<String, Object>();

					member_map.put("memberId", member.getMemberId());
					member_map.put("familyId", member.getFamilyId());
					member_map.put("userId", member.getUserId());
					UsersInfo user = new UsersInfo();
					user = userService.getById(member.getUserId());
					member_map.put("userName", user.getUserName());
					member_map.put("userImg", user.getUserImg());
					memberlist2.add(member_map);
				}
				memberlist3.add(memberlist2);
			}

		}
		if (null != familylist && !familylist.isEmpty()) {
			json.setObj(familylist);

			json.setObj2(memberlist3);
			json.setMsg("获取成功");
			json.setSuccess(true);
		} else {
			json.setMsg("你还没有加入一个家庭组呢！");
			json.setSuccess(false);
		}
		writeJson(json);
	}

	// 删除家庭组
	public void deleteFamily() throws UnsupportedEncodingException,
			ParseException {

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");

		Json json = new Json();

		if (null != userid && !userid.isEmpty() && null != familyid
				&& !familyid.isEmpty()) {

			int adminid = Integer.valueOf(userid);

			FamiliesInfo familyinfo = familyService.getById(Integer
					.valueOf(familyid));

			if (null != familyinfo && adminid == familyinfo.getAdminId()) {
				this.familyService.deleteFamily(Integer.valueOf(familyid));
				this.memberService.deleteMember(Integer.valueOf(familyid));
				this.inviteService.deleteValidates(Integer.valueOf(familyid));

				json.setMsg("删除成功");
				json.setSuccess(true);
			} else {
				json.setMsg("你不是管理员，没有权限修改！");
				json.setSuccess(false);
			}

			writeJson(json);
		}

	}

	// 搜索
	public void searchUser() throws UnsupportedEncodingException,
			ParseException {
		String search = ServletActionContext.getRequest()
				.getParameter("search");

		search = new String(search.getBytes("ISO-8859-1"), "UTF-8");

		search = java.net.URLDecoder.decode(search, "UTF-8");

		Json json = new Json();

		if (null != search && !search.isEmpty()) {
			userlist = userService.getSearchList(search);
			if (null != userlist && !userlist.isEmpty()) {
				json.setObj(userlist);
				json.setMsg("返回用户列表！");
				json.setSuccess(true);
			} else {
				json.setMsg("用户不存在！");
				json.setSuccess(false);
			}
			writeJson(json);

		}
	}

	// 邀请member

	public void inviteMember() throws UnsupportedEncodingException,
			ParseException {
		String invitedid = ServletActionContext.getRequest().getParameter(
				"invitedid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");
		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String verifyMsg = ServletActionContext.getRequest().getParameter(
				"verifyMsg");

		verifyMsg = new String(verifyMsg.getBytes("ISO-8859-1"), "UTF-8");

		verifyMsg = java.net.URLDecoder.decode(verifyMsg, "UTF-8");

		Json json = new Json();

		if (null != invitedid && !invitedid.isEmpty() && null != familyid
				&& !familyid.isEmpty()) {
			memberlist = memberService.findById(Integer.valueOf(familyid),
					Integer.valueOf(invitedid));
			if (null != memberlist && !memberlist.isEmpty()) {
				json.setMsg("用户已加入该家庭组！");
				json.setSuccess(false);
			} else {
				invitelist = inviteService.findByID(Integer.valueOf(familyid),
						Integer.valueOf(invitedid));
				if (null != invitelist && !invitelist.isEmpty()) {
					json.setMsg("验证消息已发送，请耐心等待！");
					json.setSuccess(false);
				} else {
					InviteMemberInfo inviteinfo = new InviteMemberInfo();
					inviteinfo.setFamilyId(Integer.valueOf(familyid));
					inviteinfo.setInviteUserId(Integer.valueOf(invitedid));
					inviteinfo.setUserId(Integer.valueOf(userid));
					inviteinfo.setInviteTime(new Timestamp(System
							.currentTimeMillis()));
					inviteinfo.setStatus((short) 0);
					inviteinfo.setMessage((short) 0);
					if (null != verifyMsg && !verifyMsg.isEmpty()) {
						inviteinfo.setVerifyMsg(verifyMsg);
					}

					this.inviteService.save(inviteinfo);
					json.setMsg("发送成功");
					json.setSuccess(true);
				}
			}

		}

		writeJson(json);
	}

	// 申请加入家庭组
	public void addByID() throws UnsupportedEncodingException, ParseException {

		String adminid = ServletActionContext.getRequest().getParameter(
				"adminid");

		Json json = new Json();

		if (null != adminid && !adminid.isEmpty()) {
			familylist = familyService.getListByAdminId(Integer
					.valueOf(adminid));
			if (null == familylist && familylist.isEmpty()) {
				json.setMsg("该用户还没有创建家庭组呢！");
				json.setSuccess(false);
			} else {
				json.setObj(familylist);
				json.setMsg("返回家庭组列表");
				json.setSuccess(false);
			}
		}
		writeJson(json);

	}

	public void joinFamily() throws UnsupportedEncodingException,
			ParseException {

		// String phoneNum =
		// ServletActionContext.getRequest().getParameter("phonenum");
		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");
		String verifyMsg = ServletActionContext.getRequest().getParameter(
				"verifyMsg");

		verifyMsg = new String(verifyMsg.getBytes("ISO-8859-1"), "UTF-8");

		verifyMsg = java.net.URLDecoder.decode(verifyMsg, "UTF-8");

		Json json = new Json();

		if (null != userid && !userid.isEmpty() && null != familyid
				&& !familyid.isEmpty()) {

			// int adminid = userService.findByPhoneNum(phoneNum);
			// if(adminid==0 ){
			// json.setMsg("用户不存在！");
			// json.setSuccess(false);
			// }else{
			// familylist=familyService.getListByAdminId(adminid);
			// if (null ==familylist && familylist.isEmpty()){
			// json.setMsg("该用户还没有创建家庭组呢！");
			// json.setSuccess(false);
			// }else{
			int familyid1 = Integer.valueOf(familyid);
			int adminid = familyService.getListByFamilyId(familyid1).get(0)
					.getAdminId();
			invitelist = inviteService.findByID(familyid1, adminid);
			if (null != invitelist && !invitelist.isEmpty()) {
				json.setMsg("验证消息已发送，请耐心等待！");
				json.setSuccess(false);
			} else {
				InviteMemberInfo inviteinfo = new InviteMemberInfo();
				inviteinfo.setFamilyId(familyid1);
				inviteinfo.setInviteUserId(adminid);
				inviteinfo.setUserId(Integer.valueOf(userid));
				inviteinfo.setInviteTime(new Timestamp(System
						.currentTimeMillis()));
				inviteinfo.setStatus((short) 0);
				if (null != verifyMsg && !verifyMsg.isEmpty()) {
					inviteinfo.setVerifyMsg(verifyMsg);
				}

				this.inviteService.save(inviteinfo);
				json.setMsg("发送成功");
				json.setSuccess(true);
			}

		}

		writeJson(json);
	}

	// 验证列表
	public void validatesList() throws UnsupportedEncodingException,
			ParseException {

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");

		Json json = new Json();

		if (null != userid && !userid.isEmpty()) {

			invitelist = this.inviteService.getValidatesList(Integer
					.valueOf(userid));
			if (null != invitelist && !invitelist.isEmpty()) {
				List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
				for (InviteMemberInfo listValidate : invitelist) {
					Map<String, Object> map = new HashMap<String, Object>();
					int familyid = listValidate.getFamilyId();
					map.put("familyid", familyid);
					map.put("familyname",
							this.familyService.getListByFamilyId(familyid)
									.get(0).getFamilyName());
					String sign = this.familyService
							.getListByFamilyId(familyid).get(0).getSignature();
					map.put("sign", sign);
					// map.put("userid", listValidate.getUserId());
					map.put("username",
							this.userService.getById(listValidate.getUserId())
									.getUserName());
					// String verifyMsg=listValidate.getVerifyMsg();
					map.put("verifyMsg", listValidate.getVerifyMsg());
					map.put("validateStatus", listValidate.getStatus());
					mapList.add(map);
				}
				json.setObj(mapList);
				json.setMsg("获取成功");
				json.setSuccess(true);
			} else {
				json.setMsg("没有验证消息");
				json.setSuccess(false);
			}

			writeJson(json);
		}
	}

	// 同意加入
	public void approveJoin() throws UnsupportedEncodingException,
			ParseException {

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");
		// String inviteid =
		// ServletActionContext.getRequest().getParameter("inviteid");

		Json json = new Json();

		if (userid != null && !userid.isEmpty() && familyid != null
				&& !familyid.isEmpty()) {
			memberlist = this.memberService.findById(Integer.valueOf(familyid),
					Integer.valueOf(userid));
			if (null != memberlist && !memberlist.isEmpty()) {
				json.setMsg("已加入该群");
				json.setSuccess(false);
			} else {
				UsersInfo user = this.userService.getById(Integer
						.valueOf(userid));
				FamiliesInfo familyinfo = this.familyService.getById(Integer
						.valueOf(familyid));
				familyinfo
						.setMemberNum((short) (familyinfo.getMemberNum() + 1));
				MemberInfo memberinfo = new MemberInfo();
				memberinfo.setFamilyId(Integer.valueOf(familyid));
				memberinfo.setUserId(Integer.valueOf(userid));
				List<InviteMemberInfo> invitelist = this.inviteService
						.findByID(Integer.valueOf(familyid),
								Integer.valueOf(userid));
				// if(null!=invitelist && !invitelist.isEmpty()){
				// for(int i=0; i<invitelist.size(); i++){
				// if(invitelist.get(i).getUserId()==Integer.valueOf(inviteid)){
				//
				// }
				// }
				// }
				InviteMemberInfo inviteinfo = this.inviteService
						.getById(invitelist.get(0).getInviteMemberId());
				inviteinfo.setStatus((short) 1);
				this.inviteService.save(inviteinfo);

				this.familyService.save(familyinfo);
				this.memberService.save(memberinfo);

				json.setMsg("发送成功");
				json.setSuccess(true);
			}
			writeJson(json);
		}
	}

	// 拒绝加入
	public void rejectJoin() throws UnsupportedEncodingException,
			ParseException {

		String userid = ServletActionContext.getRequest()
				.getParameter("userid");
		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");
		// String inviteid =
		// ServletActionContext.getRequest().getParameter("inviteid");

		Json json = new Json();

		if (userid != null && !userid.isEmpty() && familyid != null
				&& !familyid.isEmpty()) {
			memberlist = this.memberService.findById(Integer.valueOf(familyid),
					Integer.valueOf(userid));
			if (null != memberlist && !memberlist.isEmpty()) {
				json.setMsg("已加入该群");
				json.setSuccess(false);
			} else {
				List<InviteMemberInfo> invitelist = this.inviteService
						.findByID(Integer.valueOf(familyid),
								Integer.valueOf(userid));
				InviteMemberInfo inviteinfo = this.inviteService
						.getById(invitelist.get(0).getInviteMemberId());
				inviteinfo.setStatus((short) 2);
				this.inviteService.save(inviteinfo);

				json.setMsg("发送成功");
				json.setSuccess(true);
			}
			writeJson(json);
		}
	}

	// 成员列表
	public void memberList() throws UnsupportedEncodingException,
			ParseException {

		String familyid = ServletActionContext.getRequest().getParameter(
				"familyid");

		Json json = new Json();

		if (null != familyid && !familyid.isEmpty()) {
			memberlist = memberService
					.findByFamilyid(Integer.valueOf(familyid));
			if (null != memberlist && !memberlist.isEmpty()) {
				json.setObj(memberlist);
				json.setMsg("获取成功");
				json.setSuccess(true);
			} else {
				json.setMsg("获取失败");
				json.setSuccess(false);
			}

			writeJson(json);
		}

	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		// TODO Auto-generated method stub
		this.response = response;
	}

}
